<template>
  <div class="imgupload">
    <el-upload
      v-if="!imgUrl"
      action=""
      list-type="picture-card"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
      :limit="limit"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <div v-else class="imgbox">
      <img v-setimg="defaultimg" :src="imgUrl" alt="" @click="preimg">
      <i class="el-icon-close myicon" @click="clearImg" />
    </div>
    <!-- 预览的对话框 -->
    <el-dialog class="mydialog" title="图片预览" :visible.sync="show">
      <img :src="imgUrl" alt="">
    </el-dialog>
    <!-- 进度条 -->
    <el-progress
      v-if="showprogress"
      :percentage="percentage"
      style="width: 150px;margin-top: 10px"
      :show-text="false"
    />
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'Uploadinfo',
  props: ['imgUrl'],
  data() {
    return {
      // 控制预览框的显示与隐藏
      show: false,
      // 控制进度条显示与隐藏
      showprogress: false,
      // 定义上传到存储桶的对象
      cos: null,
      // 进度条的数据
      percentage: 0,
      // 图片显示不正确时，设置图片
      defaultimg: require('@/assets/common/bigUserHeader.png'),
      limit: 1
    }
  },
  created() {
    // 初始化存储对象
    this.cos = new COS({
      SecretId: 'AKIDkJdiW4KJ1TdW8SWJp31i8GCrFMCm45pI',
      SecretKey: 'D9oDLBk24pIUQ5TaQzHH4apnUu3vWrug'
    })
  },
  methods: {
    // 预览图片
    preimg() {
      this.show = true
    },
    // 设置自定义上传事件
    httpRequest(file) {
      // 开启进度条
      this.showprogress = true
      // 得到上传的文件
      const myfile = file.file
      // 自定义上传
      this.cos.putObject(
        {
          Bucket: 'kurumi-1306778640' /* 必须 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: myfile.name /* 必须 */,
          StorageClass: 'STANDARD',
          Body: myfile, // 上传文件对象
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
            setTimeout(() => {
              if (progressData.percent === 1) {
                // 关闭进度条
                this.showprogress = false
              }
            }, 800)
          }
        },
        (err, data) => {
          // data:上传成功后的返回值
          // err:上传出错的错误信息
          console.log('http://' + data.Location)
          // 将返回的图片地址赋值给 url
          console.log(err)
          this.$emit('update:imgUrl', 'http://' + data.Location)
        }
      )
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    clearImg() {
      this.$emit('update:imgUrl', '')
    }
  }
}
</script>

<style lang="scss" scoped>
.imgupload {
  .imgbox {
    width: 150px;
    height: 150px;
    position: relative;
    .myicon {
      position: absolute;
      top: 0px;
      right: 0px;
      background-color: #fff;
      width: 20px;
      height: 20px;
      color: #ccc;
      text-align: center;
      line-height: 20px;
      border-radius: 0 0 0 15px;
      display: none;
      &:hover {
        cursor: pointer;
      }
    }
    &:hover .myicon {
      display: block;
    }
    img {
      width: 150px;
      height: 150px;
    }
  }
  .mydialog {
    text-align: center;
    img {
      width: 400px;
      height: 400px;
    }
  }
}
</style>
